// 云函数入口文件
const cloud = require('wx-server-sdk')
const dbInit = require('./db_init')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  // 初始化数据库集合
  await dbInit.ensureCollectionsExist();
  
  // 从请求中获取参数
  const { action, params = {} } = event
  
  // 根据不同的action执行不同的操作
  switch (action) {
    case 'getGalleryList':
      return getGalleryList(params, openid);
    case 'getImageDetail':
      return getImageDetail(params, openid);
    case 'getUserImages':
      return getUserImages(params, openid);
    case 'getUserCollections':
      return getUserCollections(params, openid);
    case 'getUserLikedImages':
      return getUserLikedImages(params, openid);
    case 'likeImage':
      return likeImage(params, openid);
    case 'unlikeImage':
      return unlikeImage(params, openid);
    case 'favoriteImage':
      return favoriteImage(params, openid);
    case 'unfavoriteImage':  // 添加取消收藏的显式支持
      return favoriteImage(params, openid);
    case 'searchImages':
      return searchImages(params, openid);
    case 'addComment':
      return addComment(params, openid);
    case 'getComments':
      return getComments(params, openid);
    case 'initDB':  // 添加手动初始化数据库的接口
      return dbInit.ensureCollectionsExist();
    default:
      return {
        success: false,
        message: '未知的操作类型'
      };
  }
}

// 获取图库列表
async function getGalleryList(params, openid) {
  const { page = 1, limit = 10, category = '', sortBy = 'createTime' } = params;
  const skip = (page - 1) * limit;
  
  try {
    // 构建查询条件
    const where = { status: 'active' };
    if (category) {
      where.category = category;
    }
    
    // 获取总数
    const countResult = await db.collection('images').where(where).count();
    const total = countResult.total;
    
    // 查询数据，按时间降序排列
    const result = await db.collection('images')
      .where(where)
      .orderBy(sortBy, 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 处理图片列表，判断当前用户是否点赞和收藏
    let images = await Promise.all(result.data.map(async (image) => {
      // 查询当前用户是否点赞
      const likeResult = await db.collection('user_likes').where({
        _openid: openid,
        imageId: image._id
      }).count();
      
      // 查询当前用户是否收藏
      const favoriteResult = await db.collection('user_favorites').where({
        _openid: openid,
        imageId: image._id
      }).count();
      
      // 查询作者信息
      const userResult = await db.collection('users').where({
        _openid: image._openid
      }).get();
      
      const author = userResult.data.length > 0 ? {
        id: image._openid,
        nickName: userResult.data[0].nickName,
        avatarUrl: userResult.data[0].avatarUrl
      } : {
        id: image._openid,
        nickName: '未知用户',
        avatarUrl: '/static/images/default-avatar.png'
      };
      
      return {
        ...image,
        isLiked: likeResult.total > 0,
        isFavorited: favoriteResult.total > 0,
        author
      };
    }));
    
    return {
      success: true,
      data: {
        images,
        total,
        page,
        limit,
        hasMore: skip + images.length < total
      }
    };
  } catch (error) {
    console.error('获取图库列表失败：', error);
    return {
      success: false,
      message: '获取图库列表失败',
      error
    };
  }
}

// 获取图片详情
async function getImageDetail(params, openid) {
  const { imageId } = params;
  
  if (!imageId) {
    return {
      success: false,
      message: '缺少必要参数'
    };
  }
  
  try {
    // 查询图片信息
    const result = await db.collection('images').doc(imageId).get();
    
    if (!result.data) {
      return {
        success: false,
        message: '图片不存在'
      };
    }
    
    const image = result.data;
    
    // 查询当前用户是否点赞
    const likeResult = await db.collection('user_likes').where({
      _openid: openid,
      imageId: image._id
    }).count();
    
    // 查询当前用户是否收藏
    const favoriteResult = await db.collection('user_favorites').where({
      _openid: openid,
      imageId: image._id
    }).count();
    
    // 查询作者信息
    const userResult = await db.collection('users').where({
      _openid: image._openid
    }).get();
    
    const author = userResult.data.length > 0 ? {
      id: image._openid,
      nickName: userResult.data[0].nickName,
      avatarUrl: userResult.data[0].avatarUrl
    } : {
      id: image._openid,
      nickName: '未知用户',
      avatarUrl: '/static/images/default-avatar.png'
    };
    
    // 更新浏览次数
    await db.collection('images').doc(imageId).update({
      data: {
        viewCount: _.inc(1)
      }
    });
    
    return {
      success: true,
      data: {
        image: {
          ...image,
          isLiked: likeResult.total > 0,
          isFavorited: favoriteResult.total > 0,
          author
        }
      }
    };
  } catch (error) {
    console.error('获取图片详情失败：', error);
    return {
      success: false,
      message: '获取图片详情失败',
      error
    };
  }
}

// 获取用户发布的图片
async function getUserImages(params, openid) {
  const { userId = '', page = 1, limit = 10, category = '' } = params;
  const skip = (page - 1) * limit;
  
  // 如果没有传入userId，则获取当前用户的图片
  const targetOpenid = userId || openid;
  
  try {
    // 构建查询条件
    const where = { _openid: targetOpenid, status: 'active' };
    if (category) {
      where.category = category;
    }
    
    // 获取总数
    const countResult = await db.collection('images').where(where).count();
    const total = countResult.total;
    
    // 查询数据，按时间降序排列
    const result = await db.collection('images')
      .where(where)
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    return {
      success: true,
      data: {
        list: result.data,
        total,
        page,
        limit,
        hasMore: skip + result.data.length < total
      }
    };
  } catch (error) {
    console.error('获取用户图片失败：', error);
    return {
      success: false,
      message: '获取用户图片失败',
      error
    };
  }
}

// 获取用户收藏的图片
async function getUserCollections(params, openid) {
  const { page = 1, limit = 10, category = '' } = params;
  const skip = (page - 1) * limit;
  
  try {
    // 先获取用户收藏的图片ID
    const favoriteResult = await db.collection('user_favorites')
      .where({
        _openid: openid
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 如果没有收藏，直接返回空数组
    if (favoriteResult.data.length === 0) {
      return {
        success: true,
        data: {
          list: [],
          total: 0,
          page,
          limit,
          hasMore: false
        }
      };
    }
    
    // 获取收藏的图片ID列表
    const imageIds = favoriteResult.data.map(item => item.imageId);
    
    // 构建查询条件
    const where = {
      _id: _.in(imageIds),
      status: 'active'
    };
    if (category) {
      where.category = category;
    }
    
    // 查询图片信息
    const result = await db.collection('images')
      .where(where)
      .get();
    
    // 对图片按收藏时间排序
    const sortedImages = [];
    imageIds.forEach(id => {
      const image = result.data.find(img => img._id === id);
      if (image) {
        sortedImages.push(image);
      }
    });
    
    // 获取收藏总数
    const countResult = await db.collection('user_favorites')
      .where({ _openid: openid })
      .count();
    
    return {
      success: true,
      data: {
        list: sortedImages,
        total: countResult.total,
        page,
        limit,
        hasMore: skip + favoriteResult.data.length < countResult.total
      }
    };
  } catch (error) {
    console.error('获取用户收藏失败：', error);
    return {
      success: false,
      message: '获取用户收藏失败',
      error
    };
  }
}

// 获取用户点赞的图片
async function getUserLikedImages(params, openid) {
  const { page = 1, limit = 10, category = '' } = params;
  const skip = (page - 1) * limit;
  
  try {
    // 先获取用户点赞的图片ID
    const likeResult = await db.collection('user_likes')
      .where({
        _openid: openid
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 如果没有点赞，直接返回空数组
    if (likeResult.data.length === 0) {
      return {
        success: true,
        data: {
          list: [],
          total: 0,
          page,
          limit,
          hasMore: false
        }
      };
    }
    
    // 获取点赞的图片ID列表
    const imageIds = likeResult.data.map(item => item.imageId);
    
    // 构建查询条件
    const where = {
      _id: _.in(imageIds),
      status: 'active'
    };
    if (category) {
      where.category = category;
    }
    
    // 查询图片信息
    const result = await db.collection('images')
      .where(where)
      .get();
    
    // 对图片按点赞时间排序
    const sortedImages = [];
    imageIds.forEach(id => {
      const image = result.data.find(img => img._id === id);
      if (image) {
        sortedImages.push(image);
      }
    });
    
    // 获取点赞总数
    const countResult = await db.collection('user_likes')
      .where({ _openid: openid })
      .count();
    
    return {
      success: true,
      data: {
        list: sortedImages,
        total: countResult.total,
        page,
        limit,
        hasMore: skip + likeResult.data.length < countResult.total
      }
    };
  } catch (error) {
    console.error('获取用户点赞失败：', error);
    return {
      success: false,
      message: '获取用户点赞失败',
      error
    };
  }
}

// 点赞/取消点赞图片
async function likeImage(params, openid) {
  const { imageId } = params;
  
  if (!imageId) {
    return {
      success: false,
      message: '缺少必要参数'
    };
  }
  
  try {
    // 查询是否已点赞
    const likeResult = await db.collection('user_likes').where({
      _openid: openid,
      imageId
    }).get();
    
    const isLiked = likeResult.data.length > 0;
    
    // 如果已点赞，则取消点赞
    if (isLiked) {
      await db.collection('user_likes').doc(likeResult.data[0]._id).remove();
      await db.collection('images').doc(imageId).update({
        data: {
          likeCount: _.inc(-1)
        }
      });
      
      return {
        success: true,
        data: {
          isLiked: false,
          message: '取消点赞成功'
        }
      };
    }
    
    // 如果未点赞，则点赞
    await db.collection('user_likes').add({
      data: {
        _openid: openid,
        imageId,
        createTime: db.serverDate()
      }
    });
    await db.collection('images').doc(imageId).update({
      data: {
        likeCount: _.inc(1)
      }
    });
    
    return {
      success: true,
      data: {
        isLiked: true,
        message: '点赞成功'
      }
    };
  } catch (error) {
    console.error('点赞操作失败：', error);
    return {
      success: false,
      message: '点赞操作失败',
      error
    };
  }
}

// 收藏/取消收藏图片
async function favoriteImage(params, openid) {
  const { imageId } = params;
  
  console.log('收藏操作参数:', { imageId, openid });
  
  if (!imageId) {
    return {
      success: false,
      message: '缺少必要参数'
    };
  }
  
  try {
    // 检查图片是否存在
    const imageResult = await db.collection('images').doc(imageId).get()
      .catch(err => {
        console.error('查询图片失败:', err);
        return { data: null };
      });
    
    if (!imageResult.data) {
      console.error('图片不存在:', imageId);
      return {
        success: false,
        message: '图片不存在'
      };
    }
    
    // 查询是否已收藏
    const favoriteResult = await db.collection('user_favorites').where({
      _openid: openid,
      imageId
    }).get();
    
    console.log('收藏查询结果:', favoriteResult);
    
    const isFavorited = favoriteResult.data.length > 0;
    
    // 如果已收藏，则取消收藏
    if (isFavorited) {
      console.log('准备取消收藏:', favoriteResult.data[0]._id);
      const removeResult = await db.collection('user_favorites').doc(favoriteResult.data[0]._id).remove();
      console.log('取消收藏结果:', removeResult);
      
      const updateResult = await db.collection('images').doc(imageId).update({
        data: {
          favoriteCount: _.inc(-1)
        }
      });
      console.log('更新图片收藏数结果:', updateResult);
      
      return {
        success: true,
        data: {
          isFavorited: false,
          message: '取消收藏成功'
        }
      };
    }
    
    // 如果未收藏，则收藏
    console.log('准备添加收藏记录');
    const addResult = await db.collection('user_favorites').add({
      data: {
        _openid: openid,
        imageId,
        createTime: db.serverDate()
      }
    });
    console.log('添加收藏记录结果:', addResult);
    
    const updateResult = await db.collection('images').doc(imageId).update({
      data: {
        favoriteCount: _.inc(1)
      }
    });
    console.log('更新图片收藏数结果:', updateResult);
    
    return {
      success: true,
      data: {
        isFavorited: true,
        message: '收藏成功'
      }
    };
  } catch (error) {
    console.error('收藏操作失败：', error);
    return {
      success: false,
      message: '收藏操作失败: ' + error.message,
      error: error.message
    };
  }
}

// 搜索图片
async function searchImages(params, openid) {
  const { keyword = '', page = 1, limit = 10, category = '' } = params;
  const skip = (page - 1) * limit;
  
  try {
    // 构建查询条件
    let where = { status: 'active' };
    
    if (category) {
      where.category = category;
    }
    
    if (keyword) {
      // 模糊搜索标题、描述和标签
      where = db.command.and([
        where,
        db.command.or([
          {
            title: db.RegExp({
              regexp: keyword,
              options: 'i', // 不区分大小写
            })
          },
          {
            description: db.RegExp({
              regexp: keyword,
              options: 'i',
            })
          },
          {
            tags: db.RegExp({
              regexp: keyword,
              options: 'i',
            })
          }
        ])
      ]);
    }
    
    // 获取总数
    const countResult = await db.collection('images').where(where).count();
    const total = countResult.total;
    
    // 查询数据
    const result = await db.collection('images')
      .where(where)
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 处理图片列表，判断当前用户是否点赞和收藏
    let images = await Promise.all(result.data.map(async (image) => {
      // 查询当前用户是否点赞
      const likeResult = await db.collection('user_likes').where({
        _openid: openid,
        imageId: image._id
      }).count();
      
      // 查询当前用户是否收藏
      const favoriteResult = await db.collection('user_favorites').where({
        _openid: openid,
        imageId: image._id
      }).count();
      
      // 查询作者信息
      const userResult = await db.collection('users').where({
        _openid: image._openid
      }).get();
      
      const author = userResult.data.length > 0 ? {
        id: image._openid,
        nickName: userResult.data[0].nickName,
        avatarUrl: userResult.data[0].avatarUrl
      } : {
        id: image._openid,
        nickName: '未知用户',
        avatarUrl: '/static/images/default-avatar.png'
      };
      
      return {
        ...image,
        isLiked: likeResult.total > 0,
        isFavorited: favoriteResult.total > 0,
        author
      };
    }));
    
    return {
      success: true,
      data: {
        images,
        total,
        page,
        limit,
        hasMore: skip + images.length < total
      }
    };
  } catch (error) {
    console.error('搜索图片失败：', error);
    return {
      success: false,
      message: '搜索图片失败',
      error
    };
  }
}

// 添加评论
async function addComment(params, openid) {
  const { imageId, content, parentId = '' } = params;
  
  if (!imageId || !content) {
    return {
      success: false,
      message: '缺少必要参数'
    };
  }
  
  try {
    // 获取用户信息
    const userResult = await db.collection('users').where({
      _openid: openid
    }).get();
    
    if (userResult.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      };
    }
    
    const user = userResult.data[0];
    
    // 添加评论
    const result = await db.collection('comments').add({
      data: {
        _openid: openid,
        imageId,
        content,
        parentId,
        author: {
          id: openid,
          nickName: user.nickName,
          avatarUrl: user.avatarUrl
        },
        likeCount: 0,
        createTime: db.serverDate()
      }
    });
    
    // 更新图片评论数
    await db.collection('images').doc(imageId).update({
      data: {
        commentCount: _.inc(1)
      }
    });
    
    return {
      success: true,
      data: {
        commentId: result._id,
        message: '评论成功'
      }
    };
  } catch (error) {
    console.error('添加评论失败：', error);
    return {
      success: false,
      message: '添加评论失败',
      error
    };
  }
}

// 获取图片评论
async function getComments(params, openid) {
  const { imageId, page = 1, limit = 20 } = params;
  const skip = (page - 1) * limit;
  
  if (!imageId) {
    return {
      success: false,
      message: '缺少必要参数'
    };
  }
  
  try {
    // 获取总数
    const countResult = await db.collection('comments')
      .where({ imageId, parentId: '' })
      .count();
    
    // 先获取一级评论
    const commentsResult = await db.collection('comments')
      .where({ imageId, parentId: '' })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 获取评论的回复（二级评论）
    const comments = await Promise.all(commentsResult.data.map(async (comment) => {
      // 查询回复
      const repliesResult = await db.collection('comments')
        .where({ parentId: comment._id })
        .orderBy('createTime', 'asc')
        .get();
      
      return {
        ...comment,
        replies: repliesResult.data || []
      };
    }));
    
    return {
      success: true,
      data: {
        comments,
        total: countResult.total,
        page,
        limit,
        hasMore: skip + comments.length < countResult.total
      }
    };
  } catch (error) {
    console.error('获取评论失败：', error);
    return {
      success: false,
      message: '获取评论失败',
      error
    };
  }
}

// 取消点赞图片（为兼容API保留）
async function unlikeImage(params, openid) {
  // 实际上已在likeImage中实现了切换功能
  return likeImage(params, openid);
} 